package com.example.robertluozizhao.framecollectdemo.view.custom

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

/**
 * https://juejin.cn/post/7084969126724108301
 */
class BezierCurveView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet?,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {


    var path:Path = Path()
    var paint = Paint()


    var p1:Point = Point(100,400)
    var a:Point = Point(300,100)
    var p2:Point = Point(500,400)

    var b:Point = Point(700,100)
    var p3:Point = Point(900,400)

    var c:Point = Point(1000,700)
    var p4:Point = Point(500,1000)

    var d:Point = Point(0,700)
    var p5:Point = Point(100,400)

    init {
        paint.color = Color.RED
        paint.strokeWidth = 10f
        paint.style = Paint.Style.STROKE
        paint.isAntiAlias = true //抗锯齿super.onDraw(canvas);
    }


    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        path.moveTo(p1.x.toFloat(),p1.y.toFloat())
        for (i in 0..100){
            val bezierPoint = get2OrderBezierPoint(p1,  a,p2, i / 100.0)
            path.lineTo(bezierPoint.x.toFloat(),bezierPoint.y.toFloat())
        }
        path.moveTo(p2.x.toFloat(),p2.y.toFloat())
        for (i in 0..100){
            val bezierPoint = get2OrderBezierPoint(p2,  b,p3, i / 100.0)
            path.lineTo(bezierPoint.x.toFloat(),bezierPoint.y.toFloat())
        }
        path.moveTo(p3.x.toFloat(),p3.y.toFloat())
        for (i in 0..100){
            val bezierPoint = get2OrderBezierPoint(p3,  c,p4, i / 100.0)
            path.lineTo(bezierPoint.x.toFloat(),bezierPoint.y.toFloat())
        }
        path.moveTo(p4.x.toFloat(),p4.y.toFloat())
        for (i in 0..100){
            val bezierPoint = get2OrderBezierPoint(p4,  d,p5, i / 100.0)
            path.lineTo(bezierPoint.x.toFloat(),bezierPoint.y.toFloat())
        }

        canvas.drawPath(path,paint)
    }



    private fun get2OrderBezierPoint( p1:Point,  p2:Point,  p3:Point,  t:Double):Point{
        var x = (1 - t) * (1 - t) * p1.x + 2 * t * (1 - t) * p2.x + t * t * p3.x
        var y = (1 - t) * (1 - t) * p1.y + 2 * t * (1 - t) * p2.y + t * t * p3.y
        return Point(x.toInt(), y.toInt());
    }
}